/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-07-15
 * Time: 19:54
 */
//https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
    //给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
//
//百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大
// （一个节点也可以是它自己的祖先）。”
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Test {
    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return null;
        }
        if(root==p||root==q){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null){
            return root;
        }
        if(left==null){
            return right;
        }
        else{
            return left;
        }
    }

    public static void main(String[] args) {
        TreeNode A1=new TreeNode(1);
        TreeNode A2=new TreeNode(2);
        TreeNode A3=new TreeNode(3);
        TreeNode A4=new TreeNode(4);
        TreeNode A5=new TreeNode(5);
        TreeNode A6=new TreeNode(6);
        TreeNode A7=new TreeNode(7);
        A1.left=A2;A1.right=A3;
        A2.left=A4;A2.right=A5;
        A3.left=A6;A3.right=A7;
        TreeNode node=lowestCommonAncestor(A1,A4,A5);
        System.out.println(node.val);
    }
}
